﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace MO.ModelingClient
{
    public partial class ReleaseForm : Form
    {
        public ReleaseForm()
        {
            InitializeComponent();
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            List<EntityDefine> entitys = DataManager.FindAllEntity();
            progressBar.Maximum = entitys.Count;
            HashSet<string> allTables = GetAllTables();
            foreach (EntityDefine entity in entitys)
            {
                List<FieldDefine> fields = DataManager.FindFieldByEntityCode(entity.Code);
                if (allTables.Contains(entity.Code.ToUpper()))
                {
                    Dictionary<string, ColumnDefine> colDict = GetColumns(entity.Code);
                    List<string> list = new List<string>();
                    foreach (FieldDefine field in fields)
                    {
                        string col = field.Code.ToUpper();
                        if (colDict.ContainsKey(col))
                        {
                            ColumnDefine colDef = colDict[col];
                            string type = GetDbTyep(field.Type, field.Length);
                            if (colDef.NotNull != field.NotNull || type != colDef.Type)
                            {
                                list.Add(string.Format("MODIFY COLUMN {0}  {1} {2} ",
                                    field.Code, GetDbTyep(field.Type, field.Length), field.NotNull ? "NOT NULL" : "DEFAULT NULL"));
                            }
                        }
                        else
                        {
                            list.Add(string.Format("ADD COLUMN {0} {1} {2}  COMMENT '{3}'",
                                field.Code, GetDbTyep(field.Type, field.Length), field.NotNull ? "NOT NULL" : "DEFAULT NULL", field.Name));
                        }
                    }
                    foreach (string colName in colDict.Keys)
                    {
                        if (!fields.Any(t => t.Code.ToUpper() == colName))
                        {
                            list.Add(string.Format("DROP COLUMN {0} ", colName));
                        }
                    }
                    if (list.Count > 0)
                    {
                        string sqlStr = string.Format("ALTER TABLE {0} {1} ;", entity.Code, string.Join(",", list.ToArray()));
                        DbOperation.DB.ExecuteQuery(sqlStr);
                    }
                }
                else
                {
                    List<string> list = new List<string>();
                    foreach (FieldDefine field in fields)
                    {
                        list.Add(string.Format("{0} {1} {2} COMMENT '{3}'",
                            field.Code, GetDbTyep(field.Type, field.Length), field.NotNull ? "NOT NULL" : "DEFAULT NULL", field.Name));
                    }
                    string sqlStr = string.Format("CREATE TABLE `{0}` ({1},PRIMARY KEY (`{2}`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
                        entity.Code,
                        string.Join(" , ", list.ToArray()),
                        entity.Code + "_CODE");
                    DbOperation.DB.ExecuteQuery(sqlStr);
                }
                progressBar.Value += 1;
            }
            MessageBox.Show(this, "完成", "");
        }
        HashSet<string> GetAllTables()
        {
            DataTable table = DbOperation.DB.ExecuteDataTable("show tables");
            HashSet<string> result = new HashSet<string>();
            foreach (DataRow row in table.Rows)
            {
                result.Add(row[0].ToString().ToUpper());
            }
            return result;
        }
        Dictionary<string, ColumnDefine> GetColumns(string tableName)
        {
            DataTable table = DbOperation.DB.ExecuteDataTable("show columns from " + tableName);
            Dictionary<string, ColumnDefine> result = new Dictionary<string, ColumnDefine>();
            foreach (DataRow row in table.Rows)
            {
                string name = row["Field"].ToString().ToUpper();
                result[name] = new ColumnDefine() { Name = name, Type = row["Type"].ToString(), NotNull = row["Null"].ToString() == "NO" };
            }
            return result;
        }
        string GetDbTyep(string type, int length)
        {
            switch (type)
            {
                case FieldType.Number: return "decimal(" + length.ToString() + ",0)";
                case FieldType.Time: return "datetime";
                case FieldType.Blob: return "blob";
                default: return "varchar(" + length.ToString() + ")";
            }
        }
    }
    public class ColumnDefine
    {
        public string Name;
        public string Type;
        public bool NotNull;
    }
}
